function upload (title, content) {
    var xhr = new XMLHttpRequest()
    xhr.open('post',`/studio/track/record.json?title=${title}`)
    xhr.onload = function () {
        console.log(this.status)
        console.log(this.responseText)
    }
    xhr.send(content)
}

window.onload = function() {
    if (!navigator.mediaDevices.getUserMedia) {
        alert('浏览器版本过低，不支持媒体访问，请更新浏览器！')
        return
    }

    var constrains = {
        audio: true
    }

    var promise = navigator.mediaDevices.getUserMedia(constrains)

    function onSuccess(stream) {
        alert('用户授权成功')

        var mediaRecorder = new MediaRecorder(stream)
        mediaRecorder.onstart = function () {
            console.log('开始录制')
        }

        var data = []
        mediaRecorder.ondataavailable = function (evt) {
            console.log('数据可用')
            console.log(evt)
            data.push(evt.data)
        }

        mediaRecorder.onstop = function () {
            console.log('停止录制')
            console.log(data)
            var title = document.querySelector('#title').value.trim()
            var type = "audio/ogg; codecs=opus"
            var blob = new Blob(data,{
                type: type
            })
            var url = URL.createObjectURL(blob)
            console.log(url)

            var oAudio = document.querySelector('audio')
            oAudio.src = url

            upload(title,blob)
        }

        mediaRecorder.start(1000)

        document.querySelector('#stop').onclick = function () {
            mediaRecorder.stop()
        }

//        setTimeout(function () {
//            mediaRecorder.stop();
//        },10 * 1000)
    }

    function onError(error) {
        alert('授权过程中出现了错误' + error)
    }

    promise.then(onSuccess).catch(onError)
}